package com.example.jimmerfast.config;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * JacksonConfig
 *
 * @author L.cm
 */
@Configuration
@ConditionalOnClass(ObjectMapper.class)
@AutoConfigureBefore(value = {JacksonAutoConfiguration.class})
public class JacksonConfig {
    //请求参数不接收如下属性
//    @JsonIgnoreProperties(value = {"createdTime", "createdBy", "updatedTime", "updatedBy", "deletedInd"}, allowGetters = true)
//    @JsonMixin(Object.class)
//    public interface MyFilter {
//
//    }

    @Bean
    public static JavaTimeModule scJavaTimeModule() {
        JavaTimeModule javaTimeModule = new JavaTimeModule();

        javaTimeModule.addSerializer(Date.class, new JsonSerializer<Date>() {
            @Override
            public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                String formattedDate = DateUtil.formatDateTime(date);
                jsonGenerator.writeString(formattedDate);
            }
        });

        javaTimeModule.addDeserializer(Date.class, new JsonDeserializer<Date>() {
            @Override
            public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
                String text = jsonParser.getText();
                return DateUtil.parse(text);
            }
        });


        javaTimeModule.addSerializer(LocalDateTime.class, new JsonSerializer<LocalDateTime>() {
            @Override
            public void serialize(LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                String formattedDate = DateUtil.formatLocalDateTime(localDateTime);
                jsonGenerator.writeString(formattedDate);
            }
        });

        javaTimeModule.addDeserializer(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
            @Override
            public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
                String text = jsonParser.getText();
                DateTime date = DateUtil.parse(text);
                return DateUtil.toLocalDateTime(date);
            }
        });
        return javaTimeModule;
    }
}
